#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import rclpy
from rclpy.node import Node
from std_msgs.msg import String

from get_network_ip.ping_utils.ping_utils import load_devices_from_yaml, ping_from_yaml

class PingDevicesNode(Node):
    def __init__(self):
        super().__init__('ping_devices_node')

        # 让工具模块决定默认 YAML；也支持通过参数覆盖（可选）
        self.declare_parameter('config_path', '')
        self.config_path = self.get_parameter('config_path').value or None

        cfg = load_devices_from_yaml(self.config_path)
        self.period_sec = cfg["period_sec"]
        self.topic_name = cfg["topic_name"]

        self.pub = self.create_publisher(String, self.topic_name, 10)
        self.timer = self.create_timer(self.period_sec, self._tick)

        self.get_logger().info(
            f"PingDevicesNode 启动 | topic={self.topic_name} | period={self.period_sec}s | cfg={cfg.get('config_path', 'default')}"
        )

    def _tick(self):
        payload = ping_from_yaml(self.config_path)
        
        # 美化JSON输出：添加缩进和中文支持
        pretty_json = json.dumps(payload, ensure_ascii=False, indent=2)
        
        msg = String()
        msg.data = pretty_json  # 使用美化后的JSON
        self.pub.publish(msg)
        
        # 可选：同时打印到日志查看效果
        # self.get_logger().debug(f"发布数据:\n{pretty_json}")

def main():
    rclpy.init()
    node = PingDevicesNode()
    try:
        rclpy.spin(node)
    finally:
        node.destroy_node()
        rclpy.shutdown()

if __name__ == '__main__':
    main()